package com.kaiyidiannao.activity.SecondHandHouse;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.kaiyidiannao.adapter.CommonViewpagerAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.SecondHandHouse;
import com.kaiyidiannao.model.req.model.GetSecondHandHouseShow;
import com.kaiyidiannao.model.req.model.PostAddFavorites;
import com.kaiyidiannao.view.ActionBarView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by mark on 2014/4/14.
 */
public class SecondHandHouseDetail extends BaseActionBarActivity implements View.OnClickListener, Observer {

    private ImageView storeCall;
    private TextView sellerPhoneNum;
    private TextView secondHandHouseName;
    private ImageView collect;
    private TextView square;
    private TextView ageLimit;
    private TextView sellerDetails;
    private TextView publishTime;
    private SecondHandHouse bean;
    private String userid;
    private String action = "add";
    private String itemid;
    private String addtime;
    protected ImageLoader imageLoader; // 加载图片
    private boolean collectFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondhandhouse_detail);
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));

        initID();
        DataCenter.getInstance().addObserver(this);
        Intent intent = getIntent();


        showProgressDialog();
        itemid = intent.getStringExtra("itemid");
        addtime = intent.getStringExtra("addtime");
        if (isLogin()) {
            userid = getUserid();
            new GetSecondHandHouseShow(Integer.parseInt(itemid), userid, DataCenter.CATID_SECOND_HOUSE + "").execute(); //catid=65是死值
        } else {
            new GetSecondHandHouseShow(Integer.parseInt(itemid)).execute();
        }


        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("二手房详情");
    }

    public void setView() {
        secondHandHouseName.setText(bean.getTitle());
        square.setText(bean.getArea());
        ageLimit.setText(bean.getHouseyear());
        sellerDetails.setText(bean.getIntroduce());
        sellerPhoneNum.setText(bean.getTelephone());
        collect.setOnClickListener(this);
        storeCall.setOnClickListener(this);
        if (bean.getIs_fav()) { // 已经收藏
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucanged));
            collectFlag = true;
        } else {
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
            collectFlag = false;
        }

        publishTime.setText(bean.getAddtime());

        //八张详情图片
        imageUrlList = bean.getPicture2();
        initViewPage();
    }

    private void initID() {
        storeCall = (ImageView) findViewById(R.id.storeCall);
        sellerPhoneNum = (TextView) findViewById(R.id.sellerPhoneNum);
        secondHandHouseName = (TextView) findViewById(R.id.secondHandHouseName);
        square = (TextView) findViewById(R.id.square);
        collect = (ImageView) findViewById(R.id.collect);
        ageLimit = (TextView) findViewById(R.id.ageLimit);
        sellerDetails = (TextView) findViewById(R.id.sellerDetails);
        publishTime = (TextView)findViewById(R.id.publishTime);
        //八张详情图片
        detailViewPager = (ViewPager) findViewById(R.id.detail_ViewPager);
    }

    /**
     * 初始化8张详情图片
     */
    private ViewPager detailViewPager;
    private CommonViewpagerAdapter commonViewpagerAdapter;
    private List<View> imageList = new ArrayList<View>();
    private List<String> imageUrlList = new ArrayList<String>();

    private void initViewPage() {
        commonViewpagerAdapter = new CommonViewpagerAdapter(SecondHandHouseDetail.this, imageList, detailViewPager, imageUrlList);

        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            View view = getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            final ImageView viewpagerItemIv = (ImageView) view.findViewById(R.id.viewpagerItemIv);
            viewpagerItemIv.setImageResource(android.R.color.white);
            imageLoader.displayImage(imageUrlList.get(i), viewpagerItemIv, super.options, null);
            viewpagerItemIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    Intent intent = new Intent();
//                    intent.setClass(SecondHandHouseDetail.this, DisplayActivity.class);
//                    intent.putExtra("url", imageUrlList.get(position));
//                    startActivity(intent);
                    SecondHandHouseDetail.super.startImagePagerActivity(position, bean.getPicture());
                }
            });
            imageList.add(view);
        }

        detailViewPager.setAdapter(commonViewpagerAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataCenter.secondHandHouseShow.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }


    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        findViewById(R.id.secondhouse_detail_scrollview).setVisibility(View.GONE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog();
                findViewById(R.id.secondhouse_detail_scrollview).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                showProgressDialog();
                if (isLogin()) {
                    userid = getUserid();
                    new GetSecondHandHouseShow(Integer.parseInt(itemid), userid, DataCenter.CATID_SECOND_HOUSE + "").execute(); //catid=65是死值
                } else {
                    new GetSecondHandHouseShow(Integer.parseInt(itemid)).execute();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (null != bean) {
            if (isLogin()) {
                switch (v.getId()) {
                    case R.id.storeCall:
                        String phoneNum = (String) sellerPhoneNum.getText();
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + phoneNum));
                        startActivity(intent);
                        break;
                    case R.id.collect:
                        if (collectFlag) {
                            action = "delete";
                        } else {
                            action = "add";
                        }
                        showProgressDialog();
                        // 收藏，点赞的catid是固定的，二手房（65）
                        new PostAddFavorites(DataCenter.CATID_SECOND_HOUSE, userid, action, bean.getItemid(), bean.getTitle()).execute();//catid=65是死值
                        break;
                }
            } else {
                startLoginOrRegistered();
            }
        } else {
            showToast("详情加载失败");
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;

        closeProgressDialog();

        if (flag == DataCenter.flag.GET_SECOND_HOUSE_SHOW_SUCCESS) {
            if (null == DataCenter.secondHandHouseShow || DataCenter.secondHandHouseShow.size() == 0) {
                return;
            } else {
                bean = DataCenter.secondHandHouseShow.get(0);
                findViewById(R.id.secondhouse_detail_scrollview).setVisibility(View.VISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                if(bean != null){
                    if(bean.getPicture().length == 0){
                        detailViewPager.setBackgroundResource(R.drawable.ic_default);
                    }
                }
                setView();
            }
        } else if(flag == DataCenter.flag.GET_SECOND_HOUSE_SHOW_FAILED) {
            showReloadView();
        }

        if (flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS) {//收藏成功,关注成功\
            if (DataCenter.successFlag.equals(DataCenter.successFlag)) {
                if (collectFlag) {//从当前的关注状态变成没有关注
                    collectFlag = false;
                    //取消收藏
                    showToast(R.string.collect_cancle);
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
                } else {
                    //收藏成功
                    showToast(R.string.collect_add);
                    collectFlag = true;
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucanged));
                }
            } else {
                //收藏出现错误
                showToast(DataCenter.msg, "收藏出现错误");
            }
        }

    }
}
